package com.my.serviceimpl;


import com.alibaba.fastjson.JSONObject;
import com.my.bean.*;
import com.my.mapper.PickingMapper;
import com.my.service.PickingService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.my.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.*;


/**
	* <p>
	* 入库 服务实现类
	* </p>
	*
	* @author 崔倩倩
	* @since 2018-08-24
	*/
@Service
public class PickingServiceImpl extends ServiceImpl<PickingMapper, Picking> implements PickingService {

	@Autowired
	StockService stockService;


	@Override
	public ResultPage<Picking> selectMyPage(Picking picking, VoPage voPage,long areaid,boolean admin) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("page", (voPage.getPage() - 1)*voPage.getLimit());
		paramMap.put("limit", voPage.getLimit());
		List<Picking> list = baseMapper.selectPicking(picking,paramMap,areaid,admin);
		Integer count = baseMapper.countMyPage(picking,paramMap,areaid,admin);
		ResultPage<Picking> resultPage=new ResultPage<>();
		resultPage.setCode(0);
		resultPage.setCount(count);
		resultPage.setMsg("成功");
		resultPage.setData(list);
		return resultPage;

	}

	@Override
	@Transactional(rollbackFor = {SQLException.class})
	public String insertMa(String param,long areaid,boolean admin) throws SQLException {
		List<Stock> stocks = new ArrayList<>();
		Picking picking = JSONObject.parseObject(param, Picking.class);
		picking.setAreaId(areaid);
		if (this.insert(picking)) {
			if(admin){
				System.out.println("admin"+"------------");
				Map map=new HashMap<>();
				map.put("item_name",picking.getItemName());
				stocks=stockService.selectByMap(map);
			}else{
				Map map=new HashMap<>();
				map.put("item_name",picking.getItemName());
				map.put("areaid",areaid);
				stocks=stockService.selectByMap(map);
			}
			//如果库存中存在该物品  那就只修改数量
			if (stocks.size()>0){
				Stock stock=stocks.get(0);
				stock.setNumber(stock.getNumber()+picking.getAmount());
				if(stockService.updateById(stock)){
					return "添加成功";
				}
			}else{
				//如果库存中不存在该物品那就新增一个该物品
				Stock stock=new Stock();
				stock.setNumber(picking.getAmount());
				stock.setItemName(picking.getItemName());
				stock.setPrice(picking.getPrice());
				stock.setUpdatetime(new Date().getTime());
				stock.setSpecifications(picking.getCompany());
				stock.setType(picking.getKind());
				stock.setAreaid(areaid);
				if(stockService.insert(stock)){
					return "添加成功";
				}
			}

		}
		throw  new SQLException();

	}


}
